/*
 *  Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: info@apertum.ru
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ru.apertum.qsystem.client.forms;

import javax.swing.JDialog;
import lombok.extern.log4j.Log4j2;
import org.jdesktop.application.Action;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;
import ru.apertum.qsystem.QSystem;
import ru.apertum.qsystem.common.exceptions.ClientException;

import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToggleButton;
import javax.swing.KeyStroke;
import javax.swing.LayoutStyle;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * Created on 3 Март 2009 г., 14:54.
 *
 * @author Evgeniy Egorov
 */
@SuppressWarnings({"squid:S1192", "squid:S1172", "squid:S1450", "squid:S1604", "squid:S1161", "squid:MaximumInheritanceDepth"})
@Log4j2
public final class FAbout extends javax.swing.JDialog {

    /**
     * Используемая ссылка на диалоговое окно.
     */
    private static FAbout aboutForm;

    /**
     * Creates new form FAbout.
     */
    public FAbout(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        labelLogo.setText(FLogin.LOGO_TEXT);
        loadVersion();

        // Фича. По нажатию Escape закрываем форму
        // свернем по esc
        getRootPane().registerKeyboardAction(e -> setVisible(false),
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
    }

    /**
     * Показать информацию о сборке.
     *
     * @param parent относительно этого контрола модальность и позиционирование
     * @param modal  режим модальности
     */
    public static void showAbout(JFrame parent, boolean modal) {
        loadVersionSt();
        getForm(parent, modal, "");
        aboutForm.setVisible(true);
    }

    /**
     * Показать информацию о сборке и о версии БД.
     *
     * @param parent относительно этого контрола модальность и позиционирование
     * @param modal  режим модальности
     * @param verDB  отображаемая версия БД.
     */
    public static void showAbout(JFrame parent, boolean modal, String verDB) {
        loadVersionSt();
        getForm(parent, modal, verDB);
        aboutForm.setVisible(true);
    }

    /**
     * Опредилить Singleton.
     *
     * @param parent относительно этого контрола модальность и позиционирование
     * @param modal  режим модальности
     */
    private static void getForm(JFrame parent, boolean modal, String verDB) {
        log.info("Демонстрация информации о программе.");
        if (aboutForm == null) {
            aboutForm = new FAbout(parent, modal);
        }
        // Отцентирируем
        final Toolkit kit = Toolkit.getDefaultToolkit();
        aboutForm.setLocation(((kit.getScreenSize().width - aboutForm.getWidth()) / 2),
                ((kit.getScreenSize().height - aboutForm.getHeight()) / 2));
        aboutForm.labelDBVer.setText("".equals(verDB) ? "" : (getLocaleMessage("about.db_version") + " : " + verDB));
    }

    private static ResourceMap localeMap = null;

    /**
     * Локализация. Получить текст.
     *
     * @param key ключ.
     * @return текст на языке.
     */
    public static String getLocaleMessage(String key) {
        if (localeMap == null) {
            localeMap = Application.getInstance(QSystem.class).getContext().getResourceMap(FAbout.class);
        }
        return localeMap.getString(key);
    }

    /**
     * Загрузим параметры сборки билда из файла с версией.
     */
    public static void loadVersionSt() {
        final Properties settings = new Properties();
        try (final InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("ru/apertum/qsystem/common/version.properties")) {
            settings.load(inStream);
        } catch (IOException ex) {
            throw new ClientException("Проблемы с чтением версии. " + ex);
        }
        qdate = settings.getProperty(DATE);
        qversion = settings.getProperty(VERSION);
        qbuild = settings.getProperty(BUILD);
        qname = settings.getProperty(NAME, "");
        qversionDb = settings.getProperty(VERSION_DB);
    }

    public static final String DATE = "date";
    public static final String VERSION = "version";
    public static final String BUILD = "build";
    public static final String NAME = "name";
    public static final String VERSION_DB = "version_db";
    private static String qdate = "";
    private static String qversion = "";
    private static String qbuild = "";
    private static String qname = "";
    private static String qversionDb = "";

    public static String getQdate() {
        return qdate;
    }

    public static String getQversion() {
        return qversion;
    }

    public static String getQbuild() {
        return qbuild;
    }

    public static String getQname() {
        return qname;
    }

    public static String getQversionDb() {
        return qversionDb;
    }

    private void jToggleButtonLicKeyPressed(KeyEvent e) {
        setVisible(false);
    }

    private void loadVersion() {
        loadVersionSt();
        labelDate.setText(getLocaleMessage("about.data") + " : " + qdate);
        labelVersion.setText(getLocaleMessage("about.version") + " : " + qversion + "_" + qbuild);
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    // Generated using JFormDesigner non-commercial license
    private void initComponents() {
        ResourceBundle bundle = ResourceBundle.getBundle("ru.apertum.qsystem.client.forms.resources.FAbout");
        jPanel1 = new JPanel();
        labelRight = new JLabel();
        jToggleButtonLic = new JToggleButton();
        jLabel2 = new JLabel();
        labelDBVer = new JLabel();
        labelVersion = new JLabel();
        labelDate = new JLabel();
        labelLogo = new JLabel();
        scrollPane1 = new JScrollPane();
        jTextArea1 = new JTextArea();

        //======== this ========
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form");
        setUndecorated(true);
        setResizable(false);
        setMinimumSize(new Dimension(500, 300));
        var contentPane = getContentPane();
        contentPane.setLayout(null);

        //======== jPanel1 ========
        {
            jPanel1.setBorder(new MatteBorder(1, 1, 1, 1, Color.black));
            jPanel1.setMaximumSize(new Dimension(500, 300));
            jPanel1.setMinimumSize(new Dimension(500, 300));
            jPanel1.setName("jPanel1");
            jPanel1.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    jPanel1MouseClicked(e);
                }
            });
            jPanel1.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    jPanel1KeyPressed(e);
                }
            });

            //---- labelRight ----
            labelRight.setHorizontalAlignment(SwingConstants.CENTER);
            labelRight.setText(bundle.getString("labelRight.text"));
            labelRight.setToolTipText(bundle.getString("labelRight.toolTipText"));
            labelRight.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            labelRight.setName("labelRight");
            labelRight.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    labelRightMouseClicked(e);
                }
            });

            //---- jToggleButtonLic ----
            jToggleButtonLic.setText(bundle.getString("jToggleButtonLic.text"));
            jToggleButtonLic.setName("jToggleButtonLic");
            jToggleButtonLic.addActionListener(e -> jToggleButtonLicActionPerformed(e));
            jToggleButtonLic.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    jToggleButtonLicKeyPressed(e);
                }
            });

            //---- jLabel2 ----
            jLabel2.setHorizontalAlignment(SwingConstants.CENTER);
            jLabel2.setText(bundle.getString("jLabel2.text"));
            jLabel2.setName("jLabel2");

            //---- labelDBVer ----
            labelDBVer.setText(bundle.getString("labelDBVer.text"));
            labelDBVer.setName("labelDBVer");

            //---- labelVersion ----
            labelVersion.setText(bundle.getString("labelVersion.text"));
            labelVersion.setName("labelVersion");

            //---- labelDate ----
            labelDate.setText(bundle.getString("labelDate.text"));
            labelDate.setName("labelDate");

            //---- labelLogo ----
            labelLogo.setText("<html>logo here from code.");
            labelLogo.setFont(new Font(Font.MONOSPACED, Font.BOLD, 30));
            labelLogo.setName("labelLogo");

            GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup()
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(202, 202, 202)
                        .addComponent(jToggleButtonLic)
                        .addContainerGap(209, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup()
                            .addComponent(jLabel2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(labelLogo, GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE)
                            .addGroup(GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGap(0, 258, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                                    .addComponent(labelDate, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
                                    .addComponent(labelVersion, GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
                                    .addComponent(labelDBVer, GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)))
                            .addComponent(labelRight, GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE))
                        .addContainerGap())
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup()
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelLogo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelVersion)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelDBVer)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelDate)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelRight, GroupLayout.PREFERRED_SIZE, 13, GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jToggleButtonLic)
                        .addContainerGap(87, Short.MAX_VALUE))
            );
        }
        contentPane.add(jPanel1);
        jPanel1.setBounds(0, 0, 500, 300);

        //======== scrollPane1 ========
        {
            scrollPane1.setBorder(LineBorder.createBlackLineBorder());
            scrollPane1.setName("scrollPane1");

            //---- jTextArea1 ----
            jTextArea1.setColumns(20);
            jTextArea1.setEditable(false);
            jTextArea1.setLineWrap(true);
            jTextArea1.setRows(5);
            jTextArea1.setText(bundle.getString("jTextArea1.text"));
            jTextArea1.setWrapStyleWord(true);
            jTextArea1.setMinimumSize(new Dimension(102, 200));
            jTextArea1.setName("jTextArea1");
            jTextArea1.setPreferredSize(new Dimension(148, 220));
            jTextArea1.setBorder(null);
            jTextArea1.setFont(new Font("Arial", Font.PLAIN, 14));
            scrollPane1.setViewportView(jTextArea1);
        }
        contentPane.add(scrollPane1);
        scrollPane1.setBounds(0, 300, 500, 300);

        contentPane.setPreferredSize(new Dimension(500, 295));
        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jPanel1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPanel1KeyPressed

        setVisible(false);
    }//GEN-LAST:event_jPanel1KeyPressed

    private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseClicked

        setVisible(false);
    }//GEN-LAST:event_jPanel1MouseClicked

    private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton1KeyPressed

        setVisible(false);
    }//GEN-LAST:event_jButton1KeyPressed

    private void labelRightMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelRightMouseClicked
        try {
            String maySite = "http://www.apertum.ru";
            Desktop.getDesktop().browse(new URI(maySite));
        } catch (URISyntaxException | IOException ex) {
            log.error(ex);
        }
    }//GEN-LAST:event_labelRightMouseClicked

    private void jToggleButtonLicActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButtonLicActionPerformed
        final int delta = 300 * (jToggleButtonLic.isSelected() ? 1 : -1);
        aboutForm.setSize(aboutForm.getSize().width, aboutForm.getSize().height + delta);
    }//GEN-LAST:event_jToggleButtonLicActionPerformed

    @Action
    public void close() {
        setVisible(false);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // Generated using JFormDesigner non-commercial license
    private JPanel jPanel1;
    private JLabel labelRight;
    private JToggleButton jToggleButtonLic;
    private JLabel jLabel2;
    private JLabel labelDBVer;
    private JLabel labelVersion;
    private JLabel labelDate;
    private JLabel labelLogo;
    private JScrollPane scrollPane1;
    private JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
}
